package net.pimpas.visitor;

import java.lang.reflect.Modifier;

import net.pimpas.core.context.FrameworkContext;
import net.pimpas.core.visitor.BaseClassVisitor;
import net.pimpas.framework.PimpasFramework;
import net.pimpas.util.reflection.ReflectionUtils;

import org.apache.log4j.Logger;

public class FrameworkContextClassVisitor extends BaseClassVisitor {
	private static Logger logger = Logger.getLogger(FrameworkClassesVisitor.class);

	public FrameworkContextClassVisitor() {
		super(false, FrameworkContext.class);
	}
	
	@Override
	public boolean accept(Class<?> clazz) {
		boolean b = super.accept(clazz);
		return (b) ? 
						ReflectionUtils.isSubclass(clazz, FrameworkContext.class) && 
						!clazz.isInterface() &&
						!clazz.isEnum() && 
						!Modifier.isAbstract(clazz.getModifiers()) && 
						 Modifier.isPublic(clazz.getModifiers())
				: b;
	}

	@Override
	public void visitClass(Class<?> clazz) {
		logger.debug("[SETTING FRAMEWORK CONTEXT: "+clazz.getName()+"]");
		try {
			PimpasFramework.getInstance().setContext((FrameworkContext) clazz.newInstance());
		} catch (InstantiationException e) {
			logger.error("[ERROR]: Error setting frameworkContext", e);
		} catch (IllegalAccessException e) {
			logger.error("[ERROR]: Error setting frameworkContext", e);
		}
	}
}